<template>
  <div class="dashboard-page">
    <div class="toolbar">
      <h2>{{ merchantName }} · 商家运营概览</h2>
      <div class="actions">
        <button class="refresh" @click="refreshAll">刷新</button>
        <span class="user">{{ username }}</span>
        <button class="logout" @click="logout">退出</button>
      </div>
    </div>

    <section class="overview">
      <div class="kpi">
        <div class="kpi-item primary">
          <div class="kpi-title">今日销售额</div>
          <div class="kpi-value">¥{{ formatNumber(kpis.todaySales) }}</div>
          <div class="kpi-sub">较昨日 {{ kpis.todaySalesWow > 0 ? '+' : '' }}{{ kpis.todaySalesWow }}%</div>
        </div>
        <div class="kpi-item green">
          <div class="kpi-title">订单数</div>
          <div class="kpi-value">{{ formatNumber(kpis.orderCount) }}</div>
          <div class="kpi-sub">转化率 {{ kpis.conversion }}%</div>
        </div>
        <div class="kpi-item orange">
          <div class="kpi-title">客单价</div>
          <div class="kpi-value">¥{{ formatNumber(kpis.aov) }}</div>
          <div class="kpi-sub">较上周 {{ kpis.aovWow > 0 ? '+' : '' }}{{ kpis.aovWow }}%</div>
        </div>
        <div class="kpi-item purple">
          <div class="kpi-title">库存预警</div>
          <div class="kpi-value">{{ kpis.lowStock }}</div>
          <div class="kpi-sub">需补货SKU</div>
        </div>
      </div>
    </section>

    <section class="charts">
      <div class="chart-card">
        <div class="card-head">
          <h3>近七日销售趋势</h3>
          <div class="actions">
            <select v-model="trendDays" @change="drawTrend">
              <option value="7">近7天</option>
              <option value="14">近14天</option>
              <option value="30">近30天</option>
            </select>
          </div>
        </div>
        <div class="card-body">
          <canvas ref="trendRef" width="600" height="240"></canvas>
        </div>
      </div>

      <div class="chart-card">
        <div class="card-head">
          <h3>支付方式占比</h3>
        </div>
        <div class="card-body">
          <canvas ref="payRef" width="600" height="240"></canvas>
        </div>
      </div>
    </section>

    <section class="tables">
      <div class="table-card">
        <div class="card-head">
          <h3>热销商品 Top10</h3>
          <button class="link-btn" @click="goReport">查看报表</button>
        </div>
        <div class="table">
          <div class="thead">
            <span>排名</span>
            <span>名称</span>
            <span>销量</span>
            <span>销售额</span>
            <span>毛利率</span>
          </div>
          <div class="tbody">
            <div v-for="(r, i) in topProducts" :key="r.code" class="tr">
              <span>{{ i + 1 }}</span>
              <span class="name">{{ r.name }}</span>
              <span>{{ r.quantity }}</span>
              <span>¥{{ r.sales.toFixed(2) }}</span>
              <span>{{ r.margin }}%</span>
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ChartUtils } from '@/views/pages/pos/components/ChartUtils.js'
import { useDashboardStore } from '@/stores/dashboard.js'

const router = useRouter()
const username = ref(localStorage.getItem('merchant_last_login') || '商家')
const merchantName = ref(localStorage.getItem('merchant_name') || '示例商户')

const dashboard = useDashboardStore()

const kpis = reactive({
  todaySales: 0,
  todaySalesWow: 0,
  orderCount: 0,
  conversion: 0,
  aov: 0,
  aovWow: 0,
  lowStock: 0,
})

const topProducts = ref([])

const trendDays = ref('7')
const trendRef = ref(null)
const payRef = ref(null)

const drawTrend = () => {
  const canvas = trendRef.value
  if (!canvas) return
  const days = Number(trendDays.value)
  const { labels, values } = dashboard.buildDailySeries(days)
  ChartUtils.drawLineChart(
    canvas,
    { labels, datasets: [{ label: '销售额', data: values }] },
    { colors: ['#10b981'] }
  )
}

const drawPay = () => {
  const canvas = payRef.value
  if (!canvas) return
  const data = dashboard.getPaymentBreakdown()
  ChartUtils.drawPieChart(canvas, data, { colors: ['#10b981', '#60a5fa', '#f59e0b', '#a78bfa'], showPercentages: true })
}

const goReport = () => router.push('/pos/analysis')

const formatNumber = (n) => Number(n || 0).toLocaleString('zh-CN', { maximumFractionDigits: 2 })

const refreshAll = async () => {
  const today = dashboard.getTodayKpis()
  kpis.todaySales = today.todaySales
  kpis.todaySalesWow = today.todaySalesWow
  kpis.orderCount = today.orderCount
  kpis.conversion = today.conversion
  kpis.aov = today.aov
  kpis.aovWow = today.aovWow
  kpis.lowStock = today.lowStock

  topProducts.value = dashboard.getTopProducts(10)
  await nextTick()
  drawTrend()
  drawPay()
}

const logout = () => {
  localStorage.removeItem('merchant_last_login')
  localStorage.removeItem('merchant_token')
  router.push('/mall/login')
}

onMounted(async () => {
  dashboard.ensureInitialized()
  await refreshAll()
  const interval = Number(localStorage.getItem('refresh_interval') || 0)
  if (interval > 0) {
    const id = setInterval(refreshAll, interval * 1000)
    window.addEventListener('beforeunload', () => clearInterval(id))
  }
})
</script>

<style scoped>
.dashboard-page { display: grid; grid-template-rows: auto auto auto; gap: 14px; padding: 14px; }
.toolbar { background: #fff; border-radius: 12px; padding: 10px 14px; display: flex; align-items: center; justify-content: space-between; box-shadow: 0 1px 2px rgba(0,0,0,.04); }
.actions { display: flex; gap: 10px; align-items: center; }
.refresh { background: #10b981; border: none; color: #fff; border-radius: 8px; padding: 6px 10px; cursor: pointer; }
.logout { background: #ef4444; border: none; color: #fff; border-radius: 8px; padding: 6px 10px; cursor: pointer; }
.overview { }
.kpi { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; }
.kpi-item { background: #fff; border-radius: 12px; padding: 16px; box-shadow: 0 1px 2px rgba(0,0,0,.04); }
.kpi-title { color: #6b7280; font-size: 13px; }
.kpi-value { font-size: 22px; font-weight: 700; margin-top: 8px; color: #111827; }
.kpi-sub { margin-top: 6px; color: #10b981; font-size: 12px; }
.kpi-item.green .kpi-sub { color: #059669; }
.kpi-item.orange .kpi-sub { color: #d97706; }
.kpi-item.purple .kpi-sub { color: #7c3aed; }
.charts { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.chart-card { background: #fff; border-radius: 12px; padding: 12px; box-shadow: 0 1px 2px rgba(0,0,0,.04); }
.card-head { display: flex; align-items: center; justify-content: space-between; }
.card-body { margin-top: 10px; }
.tables { display: grid; grid-template-columns: 1fr; gap: 12px; }
.table-card { background: #fff; border-radius: 12px; padding: 12px; box-shadow: 0 1px 2px rgba(0,0,0,.04); }
.table { margin-top: 8px; }
.thead, .tr { display: grid; grid-template-columns: 80px 1fr 100px 120px 100px; gap: 8px; align-items: center; }
.thead { color: #6b7280; font-size: 12px; }
.tbody .tr { padding: 8px 0; border-top: 1px solid #f3f4f6; }
.name { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
@media (max-width: 1200px) {
  .charts { grid-template-columns: 1fr; }
  .kpi { grid-template-columns: repeat(2, 1fr); }
}
@media (max-width: 768px) {
  .kpi { grid-template-columns: 1fr; }
}
</style>


